import { modal } from 'vue-strap'
import datepicker from 'vue-datepicker'
import getDatePickerOption from '../../../../util/date-picker-option'
import { showMsg, addCGB } from '../../../../vuex/action'

export default {
  name: 'cgb-new',
  components: {
    modal: modal,
    'vue-datepicker': datepicker
  },
  data() {
    return {
      showModal: false,
      datePickerOption: getDatePickerOption(),
      cgb: {
        name: '',
        code: '',
        category: 2,
        leastMoney: '',
        increase: '',
        investmentAmount: '',
        location: '',
        shareTitle: '',
        shareContent: '',
        thoughts: '',
        homeShow: 1,
        articleTopicId: '',
        description: '',
        publishTime: ''
      }
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xAddCGB: addCGB
    }
  },
  methods: {
    validCheck() {
      var self = this
      var cgb = this.cgb
      var key
      var inputs = [
        'name',
        'code',
        'leastMoney',
        'increase',
        'investmentAmount',
        'location',
        'shareTitle',
        'shareContent',
        'thoughts',
        'articleTopicId'
      ]
      for (key of inputs) {
        if (cgb[key].length === 0) {
          return '* 标记的都为必填项'
        }
      }
      inputs = ['blockpicfile', 'picfile', 'logopicfile', 'sharepicfile']
      for (key of inputs) {
        if (self.$els[key].files.length === 0) {
          return '* 标记的都为必须上传的图片'
        }
      }
      key = null
    },
    submit() {
      var checkMsg = this.validCheck()
      if (checkMsg) {
        return this.xShowMsg({
          type: 'danger',
          content: checkMsg
        })
      }
      var formData = new FormData()
      var cgb = this.cgb
      for (var key in cgb) {
        formData.append(key, cgb[key] + '')
      }
      formData.append('blockPicFile', this.$els.blockpicfile.files[0])
      formData.append('picFile', this.$els.picfile.files[0])
      formData.append('logoPicFile', this.$els.logopicfile.files[0])
      formData.append('sharePicFile', this.$els.sharepicfile.files[0])

      this.xAddCGB(formData)
        .then(() => {
          this.$els.form.reset()
          this.showModal = false
        })
        .catch(res => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
